// 详细结果表格
function nwDetailChart() {
    this.gridData = null;
    this.lifeFieldMap = {
        'dWat': true, 'uWat': true, 'bhWat': true, 'shWat': true
    };
    this.agriFieldMap = {
        'pwirWat': true, 'pdirWat': true, 'pvirWat': true, 'pvirWat': true, 'aiWat': true, 'fishWat': true
    };
    this.indusFieldMap = {
        'indWat': true, 'nindWat': true
    };
}
nwDetailChart.prototype = {
    parseDataByArea: function (_this, formatFunc) {
        var me = this;
        var _gridData = this.gridData;
        var seriesData = [];
        $.each(_gridData, function (index, item) {
            var tempData = item.data;
            var area = formatFunc.call(_this, tempData.regCd);
            var lifeWater = agriWater = indusWater = 0;
            for (var key in tempData) {
                lifeWater += me.lifeFieldMap.hasOwnProperty(key) ? parseFloat(tempData[key]) : 0;
                agriWater += me.agriFieldMap.hasOwnProperty(key) ? parseFloat(tempData[key]) : 0;
                indusWater += me.indusFieldMap.hasOwnProperty(key) ? parseFloat(tempData[key]) : 0;
            }
            seriesData.push({
                area: area,
                data: [{
                    y: lifeWater, name: '生活'
                }, {
                    y: agriWater, name: '农业'
                }, {
                    y: indusWater, name: '工业'
                }]
            });
        });
        return seriesData;
    },
    parseDataByType: function (_this, formatFunc) {
        var me = this;
        var _gridData = this.gridData;
        var seriesDataMap = {};
        $.each(_gridData, function (index, item) {
            var tempData = item.data;
            var areaName = formatFunc.call(_this, tempData.regCd);
            if (!seriesDataMap.hasOwnProperty(areaName)) {
                seriesDataMap[areaName] = {
                    lifeWater: 0,
                    agriWater: 0,
                    indusWater: 0
                };
            }
            for (var key in tempData) {
                seriesDataMap[areaName].lifeWater += me.lifeFieldMap.hasOwnProperty(key) ? parseFloat(tempData[key]) : 0;
                seriesDataMap[areaName].agriWater += me.agriFieldMap.hasOwnProperty(key) ? parseFloat(tempData[key]) : 0;
                seriesDataMap[areaName].indusWater += me.indusFieldMap.hasOwnProperty(key) ? parseFloat(tempData[key]) : 0;
            }
        });
        var lifeData = [],
            agriData = [],
            indusData = [];
        for (var key in seriesDataMap) {
            lifeData.push({
                name: key, y: seriesDataMap[key].lifeWater
            });
            agriData.push({
                name: key, y: seriesDataMap[key].agriWater
            });
            indusData.push({
                name: key, y: seriesDataMap[key].indusWater
            });
        }
        return [{
            type: '生活', data: lifeData
        }, {
            type: '农业', data: agriData
        }, {
            type: '工业', data: indusData
        }];
    },
    getChartOption: function (title, data) {
        return {
            chart: {
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false
            },
            title: {
                text: title
            },
            tooltip: {
                headerFormat: '{series.name}<br>',
                pointFormat: '{point.name}: <b>{point.percentage:.1f}%</b>'
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                        style: {
                            color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                        }
                    },
                    showInLegend: true
                }
            },
            series: [{
                type: 'pie',
                size: '80%',
                name: '占比',
                data: data
            }]
        }
    }
}

function DefaultFactory () {
    var me = this;
    this.defaultData = null;   // 需水表格默认数据
    this.fqData = null;     // 原始分区数据
    this.areaMap = null;     // 行政分区对应的用水单元map
    this.areaList1 = null;  // 行政分区
    this.areaList2 = null;  // 用水单元
    this.getDefaultData = function () {
        var def = $.Deferred();
        const defaultDataUrl = "/jsite-szy-dispatch/a/szy/dispatch/waterPred/default?proCd=" + $.dispatch.getProCd();
        $.getJSON(defaultDataUrl, function (data) {
            me.defaultData = data;
            def.resolve();
        });
        return def.promise();
    }
    this.getFqData = function () {
        var def = $.Deferred();
        $.getJSON("/jsite-szy-dispatch/a/szy/dispatch/fqData", function (data) {
            me.fqData = data;
            me.formatFqData();
            def.resolve();
        });
        return def.promise();
    }
    this.getSolutionInfo = function (calc) {
        var def = $.Deferred();
        $.getJSON("/jsite-szy-dispatch/a/szy/dispatch/ddsRdP/get/" + $.dispatch.getProCd() , function (data) {
            calc.year = data.yr - 2015;
            def.resolve();
        });
        return def.promise();
    }
    this.formatFqData = function () {
        var map = {};
        var list1 = [];
        var list2 = [];
        $.each(me.fqData, function (index, obj) {
            list1.push({
                adCd: obj.adCd,
                adNm: obj.adNm
            });
            $.merge(list2, obj.waList);
            var tempList = [];
            $.each(obj.waList, function (index2, obj2) {
                tempList.push(obj2.wrcsCd);
            });
            map[obj.adCd] = tempList;
        });
        me.areaMap = map;
        me.areaList1 = list1;
        me.areaList2 = list2;
    }
}
DefaultFactory.prototype = {
    getDataByTypeAndCds: function (type, cdField, cdList) {
        var data = this.defaultData[type];
        var cData = [];
        $.each(cdList, function (index0, cd) {
            $.each(data, function (index1, obj1) {
                if (cd === obj1[cdField]) {
                    cData.push(obj1);
                }
            });
        });
        return cData;
    }
}

function NeedWaterCalc() {
    var me = this;
    me.year = 0;
    me.cRegCdList = [];
}
NeedWaterCalc.prototype = {
    init: function (df) {
        var me = this;
        var totalData = df.defaultData.p0;
        var baseData = df.defaultData.p1;
        var rateData = df.defaultData.p2;
        var limitData = df.defaultData.p3;
        var paramData = df.defaultData.p4;
        var monthParamData = df.defaultData.p5;
        var resultData = df.defaultData.p6;
        var monthData = df.defaultData.p7;
        $.each(totalData, function (index1, row1) {
            var adCd = row1.adCd;
            var regCdList = df.areaMap[adCd];
            var tTotal = 0;
            $.each(regCdList, function (index2, val) {
                $.each(baseData, function (index3, row2) {
                    var regCd = row2.regCd;  // 用水单元编号
                    if (val === regCd) {
                        var trd = $.grep(rateData, function (obj1, index4) { 
                            return obj1.adCd === adCd;
                        });
                        var tld = $.grep(limitData, function (obj2, index5) { 
                            return obj2.adCd === adCd;
                        });
                        var tpd = $.grep(paramData, function (obj3, index6) { 
                            return obj3.adCd === adCd;
                        });
                        var lifeResult = me.life(row2, trd[0], tld[0], tpd[0]);
                        var agriResult = me.agri(row2, trd[0], tld[0], tpd[0]);
                        var industryResult = me.industry(row2, trd[0], tld[0], tpd[0]);
                        var tempRData = $.grep(resultData, function (obj4, index7) { 
                            return obj4.regCd === regCd;
                        });
                        if (tempRData.length > 0) {
                            $.extend(tempRData[0], lifeResult, agriResult, industryResult);
                            var t = $.extend({}, lifeResult, agriResult, industryResult);
                            for (var key in t) {
                                tTotal += t[key];
                            }
                        }
                        me.setMonthData(adCd, regCd, tempRData[0], monthParamData, monthData);
                    }
                });
            });
            $.extend(row1, {"tw": NumberToFixed(tTotal / 10000, 3)});
        });
    },
    // 计算逐月分配数据
    setMonthData: function (adCd, regCd, resultRow, monthParamData, monthData) {
        var me = this;
        var data1 = [];
        if (!adCd) {
            data1 = monthParamData;
            resultRow = resultRow.data;
        } else {
            data1 = $.grep(monthParamData, function (obj, index) { 
                return obj.adCd === adCd;
            });
        }
        
        var data2 = $.grep(monthData, function (obj, index) { 
            return obj.regCd === regCd;
        });
        $.each(data1, function (index, row) {
            if (!adCd) {
                row = row.data;
            }
            var month = row.month;
            var tempMD = $.grep(data2, function (obj, index2) { 
                return obj.month === month;
            });
            if (tempMD.length > 0) {
                $.extend(tempMD[0], {
                    "dWat": NumberToFixed(resultRow.dWat * row.pwmCoe),
                    "uWat": NumberToFixed(resultRow.uWat * row.pwmCoe),
                    "bhWat": NumberToFixed(resultRow.bhWat * row.pwmCoe),
                    "shWat": NumberToFixed(resultRow.shWat * row.pwmCoe),
                    "pwirWat": NumberToFixed(resultRow.pwirWat * row.awmCoe),
                    "pdirWat": NumberToFixed(resultRow.pdirWat * row.awmCoe),
                    "pvirWat": NumberToFixed(resultRow.pvirWat * row.awmCoe),
                    "fiWat": NumberToFixed(resultRow.fiWat * row.lmyCoe),
                    "aiWat": NumberToFixed(resultRow.aiWat * row.lmyCoe),
                    "fishWat": NumberToFixed(resultRow.fishWat * row.lmyCoe),
                    "indWat": NumberToFixed(resultRow.indWat * row.iwmCoe),
                    "nindWat": NumberToFixed(resultRow.nindWat * row.iwmCoe)
                });
            }
        });
    },
    all: function () {
        var me = this;
        me.cRegCdList = [];
        var baseData = Ext.data.StoreManager.lookup('wdp_store1').getData().items;
        var rateData = Ext.data.StoreManager.lookup('wdp_store2').getData().items[0].data;
        var limitData = Ext.data.StoreManager.lookup('wdp_store3').getData().items[0].data;
        var paramData = Ext.data.StoreManager.lookup('wdp_store4').getData().items[0].data;
        var resultData = Ext.data.StoreManager.lookup('wdp_store6').getData().items;
        var total = 0;
        $.each(baseData, function (index, row) {
            var rowData = row.data;
            var regCd = rowData.regCd;  // 用水单元编号
            me.cRegCdList.push(regCd);
            var lifeResult = me.life(rowData, rateData, limitData, paramData);
            var agriResult = me.agri(rowData, rateData, limitData, paramData);
            var industryResult = me.industry(rowData, rateData, limitData, paramData);
            var tempRData = $.grep(resultData, function (obj, index) { 
                return obj.data.regCd === regCd;
            });
            if (tempRData.length > 0) {
                $.extend(tempRData[0].data, lifeResult, agriResult, industryResult);
                var t = $.extend({}, lifeResult, agriResult, industryResult);
                for (var key in t) {
                    total += t[key];
                }
            }
        });
        return NumberToFixed(total / 10000, 3);
    },
    // 生活需水
    life: function (rowData, rateData, limitData, paramData) {
        // 预测年城市人口
        var f_townPp = rowData.townPp * Math.pow(1 + rateData.dPopGr / 100, this.year);
        // 预测年农村人口
        var f_ruralPp =(rowData.townPp + rowData.ruralPp) * Math.pow(1 + rateData.totPopGr / 100, this.year) - f_townPp;
        // 预测年城市净需水
        var j_dWat = f_townPp * limitData.dWun * 365 / 1000;
        // 预测年农村净需水
        var j_uWat = f_ruralPp * limitData.rWun * 365 / 1000;

        // 预测年大牲畜数量
        var f_llsNum = rowData.llsNum * Math.pow(1 + rateData.bhGr / 100, this.year);
        // 预测年小牲畜数量
        var f_slsNum = rowData.slsNum * Math.pow(1 + rateData.shGr / 100, this.year);
        // 预测年大牲畜净需水
        var j_bhWat = f_llsNum * limitData.bhWun * 365 / 1000;
        // 预测年小牲畜净需水
        var j_shWat = f_llsNum * limitData.shWun * 365 / 1000;

        // 预测年城市总需水
        var dWat = j_dWat / (1 - paramData.dWsLr / 100);
        // 预测年农村总需水
        var uWat = j_uWat * (paramData.crwsR / 100 / (1 - paramData.crwsLr / 100) + 1 - paramData.crwsR / 100);
        // 预测年小牲畜总需水
        var bhWat = j_bhWat * (paramData.crwsR / 100 / (1 - paramData.crwsLr / 100) + 1 - paramData.crwsR / 100);
        // 预测年大牲畜总需水
        var shWat = j_shWat * (paramData.crwsR / 100 / (1 - paramData.crwsLr / 100) + 1 - paramData.crwsR / 100);

        return {
            'dWat': NumberToFixed(dWat), 'uWat': NumberToFixed(uWat), 
            'bhWat': NumberToFixed(bhWat), 'shWat': NumberToFixed(shWat)
        };
    },
    // 农业需水
    agri: function (rowData, rateData, limitData, paramData) {
        // 预测年农田有效灌溉面积
        var f_pweirA = rowData.pweirA * Math.pow(1 + rateData.pwirraGr / 100, this.year);
        // 预测年农田需水
        var pwirWat = f_pweirA * limitData.pwirWun / (paramData.pwirR / 100);

        // 预测年水浇地有效灌溉面积
        var f_pdeirA = rowData.pdeirA * Math.pow(1 + rateData.pdirraGr / 100, this.year);
        // 预测年水浇地需水
        var pdirWat = f_pdeirA * limitData.pdirWun / (paramData.pdirR / 100);

        // 预测年菜田有效灌溉面积
        var f_pveirA = rowData.pveirA * Math.pow(1 + rateData.pvirraGr / 100, this.year);
        // 预测年菜田需水
        var pvirWat = f_pveirA * limitData.pvirWun / (paramData.pvirR / 100);

        // 预测年林果地有效灌溉面积
        var f_tfgA = rowData.tfgA * Math.pow(1 + rateData.fiaGr / 100, this.year);
        // 预测年林果地需水
        var fiWat = f_tfgA * limitData.fiWun / (paramData.fiR / 100);

        // 预测年草场有效灌溉面积
        var f_airrA = rowData.airrA * Math.pow(1 + rateData.aiaGr / 100, this.year);
        // 预测年草场需水
        var aiWat = f_airrA * limitData.aiWun / (paramData.aiR / 100);

        // 预测年鱼塘有效灌溉面积
        var f_fishA = rowData.fishA * Math.pow(1 + rateData.fishaGr / 100, this.year);
        // 预测年鱼塘需水
        var fishWat = f_fishA * limitData.fishWun;

        return {
            "pwirWat": NumberToFixed(pwirWat), "pdirWat": NumberToFixed(pdirWat), "pvirWat": NumberToFixed(pvirWat), 
            "fiWat": NumberToFixed(fiWat), "aiWat": NumberToFixed(aiWat), "fishWat": NumberToFixed(fishWat)
        };
    },
    // 工业需水
    industry: function (rowData, rateData, limitData, paramData) {
        // 预测年工业（火核）总产值
        var f_indEpv = rowData.indEpv * Math.pow(1 + rateData.indGr / 100, this.year);
        // 预测年工业（火核）净需水
        var j_indWat = f_indEpv * limitData.indWun;
        // 预测年工业（火核）需水
        var indWat = j_indWat / (1 - paramData.indLr / 100);
        // 预测年工业（非火核）总产值
        var f_nindEpv = rowData.nindEpv * Math.pow(1 + rateData.nindGr / 100, this.year);
        // 预测年工业（非火核）净需水
        var j_nindWat = f_nindEpv * limitData.nindWun;
        // 预测年工业（非火核）需水
        var nindWat = j_nindWat / (1 - paramData.indLr / 100);
        return {
            "indWat": NumberToFixed(indWat), "nindWat": NumberToFixed(nindWat)
        };
    }
}

function NumberToFixed(number, fix) {
    return parseFloat(number.toFixed(fix || 1));
}

// 需水统计弹出框
function nwStatisticsFactory(df) {
    var me = this;
    this.data = [];
    this.parseData1 = [];
    this.parseData2 = [];
    var getAdAndRegNm = function (regCd) {
        var regNm = '';
        var adNm = '';
        $.each(df.fqData, function (index, obj) {
            adNm = obj.adNm;
            var regList = obj.waList;
            $.each(regList, function (index2, obj2) {
                if (regCd === obj2.wrcsCd) {
                    regNm = obj2.wrcsNm;
                    return false;
                }
            });
            if (regNm !== '') {
                return false;
            }
        });
        return {regNm: regNm, adNm: adNm};
    }
    var parse = function (getAdAndRegNm) {
        var result = df.defaultData.p6;
        var parseResults = [];
        $.each(result, function (index, obj) {
            var name = getAdAndRegNm(obj.regCd);
            var life = NumberToFixed(obj.dWat + obj.uWat + obj.bhWat + obj.shWat);
            var agri = NumberToFixed(obj.pdirWat + obj.pvirWat + obj.pwirWat + obj.aiWat + obj.fiWat + obj.fishWat);
            var indus = NumberToFixed(obj.indWat + obj.nindWat);
            var total = NumberToFixed(life + agri + indus);
            parseResults.push({
                area: name.adNm,
                area2: name.regNm,
                life: life,
                agri: agri,
                indus: indus,
                total: total
            });
        });
        me.data = parseResults;
    };
    (function () {
        parse(getAdAndRegNm);
    }());
}
nwStatisticsFactory.prototype = {
    getGridDataByType: function (type) {
        var _data = this.data;
        type = type || '1';
        var parseData = {};
        var typeFiled = type === '1' ? 'area' : (type === '2' ? 'area2' : 'area');
        var typeFiled2 = type === '1' ? 'area2' : (type === '2' ? 'area' : 'area2');
        $.each(_data, function (index, item) {
            var tempType = item[typeFiled];
            if (!parseData.hasOwnProperty(tempType)) {
                parseData[tempType] = [];
            }
            parseData[tempType].push({
                area2: item[typeFiled2],
                life: parseFloat(item.life).toFixed(2),
                agri: parseFloat(item.agri).toFixed(2),
                indus: parseFloat(item.indus).toFixed(2),
                total: parseFloat(item.total).toFixed(2)
            });
        });
        for (var key in parseData) {
            var totalLife = totalAgri = totalIndus = totalWhole = 0.0;
            $.each(parseData[key], function (index, item) {
                totalLife += parseFloat(item.life);
                totalAgri += parseFloat(item.agri);
                totalIndus += parseFloat(item.indus);
                totalWhole += parseFloat(item.total);
            });
            parseData[key].push({ area2: '合计', life: totalLife.toFixed(2), agri: totalAgri.toFixed(2), indus: totalIndus.toFixed(2), total: totalWhole.toFixed(2) });
        }
        var parseData2 = [];
        for (var key in parseData) {
            $.each(parseData[key], function (index, item) {
                var area = '';
                if (index === 0) {
                    area = key;
                }
                parseData2.push({ area: area, area2: item.area2, life: item.life, agri: item.agri, indus: item.indus, total: item.total });
            });
        }
        if (type === "1") {
            this.parseData1 = parseData;
        } else if (type === '2') {
            this.parseData2 = parseData;
        }
        return parseData2;
    },
    getSankeyChartData: function () {
        var tempData1 = this.parseData1;
        var tempData2 = this.parseData2;
        var dataNodes = [];
        var dataLinks = [];
        for (var key in tempData2) {
            dataNodes.push({ name: key });
            $.each(tempData2[key], function (index, item) {
                if (item.area2 !== '合计') {
                    dataLinks.push({
                        source: key, target: item.area2, value: parseFloat(item.total)
                    });
                }
            });
        }
        for (var key2 in tempData1) {
            $.each(tempData1[key2], function (index, obj) {
                if (obj.area2 === '合计') {
                    dataLinks.push({
                        source: key2, target: '生活', value: parseFloat(obj.life)
                    });
                    dataLinks.push({
                        source: key2, target: '农业', value: parseFloat(obj.agri)
                    });
                    dataLinks.push({
                        source: key2, target: '工业', value: parseFloat(obj.indus)
                    });
                }
            });
            dataNodes.push({ name: key2 });
        }
        dataNodes.push({ name: '生活' });
        dataNodes.push({ name: '农业' });
        dataNodes.push({ name: '工业' });
        return {
            links: dataLinks,
            nodes: dataNodes
        }
    },
    getChartOption: function (type) {
        var titleMap = {
            '1': '行政分区各项用水情况',
            '2': '水资源分区各项用水情况'
        };
        var dataMap = {
            '1': this.parseData1,
            '2': this.parseData2
        };
        var parseData = dataMap[type];
        var lifeData = [],
            agriData = [],
            indusData = [];
        var categories = [];
        for (var key in parseData) {
            categories.push(key);
            $.each(parseData[key], function (index, item) {
                if (item.area2 === '合计') {
                    lifeData.push(parseFloat(item.life));
                    agriData.push(parseFloat(item.agri));
                    indusData.push(parseFloat(item.indus));
                }
            });
        }
        return {
            chart: {
                type: 'column'
            },
            title: {
                text: titleMap[type]
            },
            xAxis: {
                categories: categories
            },
            yAxis: {
                min: 0,
                title: {
                    text: '用水量(m³)'
                },
                stackLabels: {
                    enabled: true,
                    style: {
                        fontWeight: 'bold',
                        color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
                    }
                }
            },
            legend: {
                layout: 'horizontal',
                align: 'center',
                verticalAlign: 'bottom',
                borderWidth: 0
            },
            tooltip: {
                formatter: function () {
                    return '<b>' + this.x + '</b><br/>' +
                        this.series.name + ': ' + this.y + '<br/>' +
                        '总量: ' + this.point.stackTotal;
                }
            },
            plotOptions: {
                column: {
                    stacking: 'normal',
                    dataLabels: {
                        enabled: false,
                        color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
                        style: {
                            textShadow: '0 0 3px black'
                        }
                    }
                }
            },
            series: [{
                name: '生活',
                data: lifeData
            }, {
                name: '农业',
                data: agriData
            }, {
                name: '工业',
                data: indusData
            }],
            credits: {
                enabled: false
            }
        };
    },
    getChartOption2: function (data) {
        return {
            title: {
                text: '全流域使用情况',
                textAlign: 'center',
                left: '40%'
            },
            tooltip: {
                trigger: 'item',
                triggerOn: 'mousemove'
            },
            series: [{
                top: 35,
                type: 'sankey',
                layout: 'none',
                data: data.nodes,
                links: data.links,
                itemStyle: {
                    normal: {
                        borderWidth: 1,
                        borderColor: '#aaa'
                    }
                },
                lineStyle: {
                    normal: {
                        // color: 'source',
                        curveness: 0.5
                    }
                }
            }]
        };
    }
}

Ext.define('Admin.view.needWater.waterDemandPrediction.WaterDemandPredController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.waterDemandPredController',
    views: ['Admin.view.needWater.waterDemandPrediction.WaterDemandPred'],
    beforeRender: function () {
        this.showNum = 0;
        this.wdtab2ChartId = null;
    },
    /* 需水 tab-content 初始化 */
    afterRenderInit: function () {
        var me = this;
        me.showNum++;
        if (me.showNum == 1) {
            me.defaultFac = new DefaultFactory();
            me.modelCalc = new NeedWaterCalc();
            me.nwdChart = new nwDetailChart();
            var myMask = new Ext.LoadMask($.dispatch.componentQuery('waterDemandPred'), { 
                msg: "正在加载数据..." 
            });
            myMask.show();
            me.myMask = myMask;
            $.when(me.defaultFac.getDefaultData(), 
            me.defaultFac.getFqData(), 
            me.defaultFac.getSolutionInfo(me.modelCalc))
            .then(function () {
                // 初始化计算数据
                me.modelCalc.init(me.defaultFac);
                var data = me.defaultFac.defaultData;
                Ext.data.StoreManager.lookup('wdp_store0').setData(data.p0);
                me.sumNeedWater();
                var grid0 = me.lookupReference('grid0');
                grid0.getSelectionModel().select(0);
                // grid0.getView().fireEvent('itemclick', grid0, 0);
                me.changeArea(grid0, me.defaultFac.defaultData.p0[0]['adCd']);
            });
        }
    },
    saveOrUpdate: function (df) {
        var df = this.defaultFac;
        var myMask = new Ext.LoadMask($.dispatch.componentQuery('waterDemandPred'), { 
            msg: "正在保存..." 
        });
        myMask.show();
        var data = {
            p1: df.defaultData.p1,
            p2: df.defaultData.p2,
            p3: df.defaultData.p3,
            p4: df.defaultData.p4,
            p5: df.defaultData.p5,
            p6: df.defaultData.p6,
            p7: df.defaultData.p7
        };
        var url = '/jsite-szy-dispatch/a/szy/dispatch/waterPred/saveOrUpdate?proCd=' + $.dispatch.getProCd();
        $.ajax({
            url: url,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data)
        })
        .done(function(res) { 
            if (res) {
                Ext.Msg.alert("提示信息", "保存成功!");
            }
        })
        .fail(function() { 
            Ext.Msg.alert("提示信息", "保存失败!");
        })
        .always(function() { 
            myMask.hide();
        });
    },
     // 选择不同的行政区
    changeArea: function (_grid, _selectRrow) {
        var me = this;
        var df = me.defaultFac;
        var adCd = typeof _selectRrow === 'string' ? _selectRrow : _selectRrow.get('adCd');
        var regCdList = me.defaultFac.areaMap[adCd];
        Ext.data.StoreManager.lookup('wdp_store1').setData(df.getDataByTypeAndCds("p1", "regCd", regCdList));
        Ext.data.StoreManager.lookup('wdp_store2').setData(df.getDataByTypeAndCds("p2", "adCd", [adCd]));
        Ext.data.StoreManager.lookup('wdp_store3').setData(df.getDataByTypeAndCds("p3", "adCd", [adCd]));
        Ext.data.StoreManager.lookup('wdp_store4').setData(df.getDataByTypeAndCds("p4", "adCd", [adCd]));
        Ext.data.StoreManager.lookup('wdp_store5').setData(df.getDataByTypeAndCds("p5", "adCd", [adCd]));
        Ext.data.StoreManager.lookup('wdp_store6').setData(df.getDataByTypeAndCds("p6", "regCd", regCdList));
        var monthData = me.defaultFac.getDataByTypeAndCds("p7", "regCd", regCdList);
        Ext.data.StoreManager.lookup('wdp_store7').setData(this.parseMonthData(monthData));
        if (typeof me.myMask === 'object') {
            me.myMask.hide();
            me.myMask = undefined;
        }
        Ext.getCmp('wd-tab2-chart-panel').fireEvent('resize');
        this.lookup('wdTab3Chart1').fireEvent('resize');
    },
    // 参数设置表格数据改动，自动计算需水详细结果
    // 相关表格：社会经济指标、社会经济发展参数、用水定额、用书参数、逐月分配系数
    clacDeatilNeedWater: function () {
        // 行政区总需水
        var total = this.modelCalc.all();
        var selects = this.lookupReference('grid0').getSelection();
        var df = this.defaultFac;
        if (selects.length > 0) {
            $.extend(selects[0].data, {"tw": total});
            Ext.data.StoreManager.lookup('wdp_store0').setData(df.defaultData.p0);
        }
        this.sumNeedWater();
        Ext.data.StoreManager.lookup('wdp_store6')
        .setData(df.getDataByTypeAndCds("p6", "regCd", this.modelCalc.cRegCdList));
        // 计算逐月需水结果
        this.clacMonthNeedWater();
        Ext.getCmp('wd-tab2-chart-panel').fireEvent('resize');
    },
    // 计算逐月需水结果
    clacMonthNeedWater: function () {
        var df = this.defaultFac;
        var clac = this.modelCalc;
        var monthParamData = Ext.data.StoreManager.lookup('wdp_store5').getData().items;
        var resultData = Ext.data.StoreManager.lookup('wdp_store6').getData().items;
        var cRegCdList = [];
        $.each(resultData, function (index, row) {
            cRegCdList.push(row.data.regCd);
        });
        var monthData = df.getDataByTypeAndCds("p7", "regCd", cRegCdList);
        $.each(resultData, function (index, row) {
            var regCd = row.data.regCd;
            clac.setMonthData(null, regCd, row, monthParamData, monthData);
        });
        Ext.data.StoreManager.lookup('wdp_store7').setData(this.parseMonthData(monthData));
        this.lookup('wdTab3Chart1').fireEvent('resize');
    },
    parseMonthData: function (data) {
        var parseData = {};
        $.each(data, function (index, obj) {
            var month = obj.month;
            if (!parseData.hasOwnProperty(month)) {
                parseData[month] = {};
            }
            for (var key in obj) {
                if (key !== 'regCd' && key !== 'month') {
                    if (!parseData[month].hasOwnProperty(key)) {
                        parseData[month][key] = 0;
                    }
                    parseData[month][key] += obj[key];
                }
            }
        });
        var parseData2 = [];
        for (var month in parseData) {
            parseData2.push($.extend({}, {"month": month}, parseData[month]));
        }
        return parseData2;
    },
    sumNeedWater: function () {
        var data = Ext.data.StoreManager.lookup('wdp_store0').getData().items;
        var num = 0;
        $.each(data, function (index, row) {
            num += row.data.tw;
        });
        $('#sumNeedWater').html(num.toFixed(2));
    },
    // 转换 用水区域 编号为名称
    formatAdCdToName: function (value) {
        var data = this.defaultFac.areaList1;
        var name = '';
        $.each(data, function (index, obj) {
            if (value === obj.adCd) {
                name = obj.adNm;
                return false;
            }
        });
        return name;
    },
    // 转换 用水单元 编号为名称
    formatRegCdToName: function (value) {
        var data = this.defaultFac.areaList2;
        var name = '';
        $.each(data, function (index, obj) {
            if (value === obj.wrcsCd) {
                name = obj.wrcsNm;
                return false;
            }
        });
        return name;
    },
    /**
     * 需水统计
     */
    popStatisticsModal: function () {
        var sf = new nwStatisticsFactory(this.defaultFac);
        var grid = new Ext.grid.GridPanel({
            cls: 'shadow',
            style: 'border: 1px solid #ccc',
            loadingText: '加载中',
            stripeRows: true,
            columnLines: true,
            forceFit: true,
            columns: [{
                header: '行政区',
                dataIndex: 'area',
                editor: 'textfield',
                align: 'center'
            }, {
                header: '水资源分区',
                dataIndex: 'area2',
                editor: 'textfield',
                align: 'center'
            }, {
                header: '合计用水',
                dataIndex: 'total',
                editor: 'textfield',
                align: 'right'
            }, {
                header: '生活',
                dataIndex: 'life',
                editor: 'textfield',
                align: 'right'
            }, {
                header: '农业',
                dataIndex: 'agri',
                editor: 'textfield',
                align: 'right'
            }, {
                header: '工业',
                dataIndex: 'indus',
                editor: 'textfield',
                align: 'right'
            }],
            store: {
                fields: ['area', 'area2', 'total', 'life', 'agri', 'indus'],
                data: sf.getGridDataByType('1')
            }
        });
        var grid2 = new Ext.grid.GridPanel({
            cls: 'shadow',
            style: 'border: 1px solid #ccc',
            loadingText: '加载中',
            stripeRows: true,
            columnLines: true,
            forceFit: true,
            columns: [{
                header: '水资源分区',
                dataIndex: 'area',
                editor: 'textfield',
                align: 'center'
            }, {
                header: '行政区',
                dataIndex: 'area2',
                editor: 'textfield',
                align: 'center'
            }, {
                header: '合计用水',
                dataIndex: 'total',
                editor: 'textfield',
                align: 'right'
            }, {
                header: '生活',
                dataIndex: 'life',
                editor: 'textfield',
                align: 'right'
            }, {
                header: '农业',
                dataIndex: 'agri',
                editor: 'textfield',
                align: 'right'
            }, {
                header: '工业',
                dataIndex: 'indus',
                editor: 'textfield',
                align: 'right'
            }],
            store: {
                fields: ['area', 'area2', 'total', 'life', 'agri', 'indus'],
                data: sf.getGridDataByType('2')
            }
        });
        var panel = new Ext.panel.Panel({
            flex: 2,
            margin: 10,
            layout: 'card',
            items: [grid, grid2]
        });
        var tjChart1;
        Ext.create('Ext.window.Window', {
            title: '需水统计',
            width: '90%',
            height: '80%',
            modal: true,
            layout: {
                type: 'vbox',
                align: 'stretch'
            },
            items: [{
                height: 40,
                items: [{
                    xtype: 'segmentedbutton',
                    // cls: 'x-box-item',
                    docked: 'right',
                    style: 'background-color: #ddd',
                    right: 0,
                    margin: '10 10 0 10',
                    minWidth: 200,
                    items: [{
                        width: 100,
                        text: '行政分区',
                        pressed: true,
                        listeners: {
                            "click": function () {
                                panel.setActiveItem(0);
                                // grid.reconfigure(store, columns);
                                // grid.store.loadData(sf.getGridDataByType('1'));
                                $('#tjChart2').highcharts(sf.getChartOption('1'));
                            }
                        }
                    }, {
                        width: 100,
                        text: '水资源分区',
                        listeners: {
                            "click": function () {
                                panel.setActiveItem(1);
                                // grid.reconfigure(store, columns);
                                // grid.store.loadData(sf.getGridDataByType('1'));
                                $('#tjChart2').highcharts(sf.getChartOption('2'));
                            }
                        }
                    }]
                }]
            }, {
                height: '97%',
                layout: {
                    type: 'vbox',
                    align: 'stretch'
                },
                items: [panel, {
                    flex: 3,
                    margin: '0 10 30 10',
                    html: '<div class="row-chart" style="width: 100%; height: 100%;">' +
                    '<div id="tjChart1" style="height: 100%;flex: 1 1 40%;"></div>' +
                    '<div id="tjChart2" style="height: 100%;flex: 1 1 60%;"></div>' +
                    '</div>',
                    listeners: {
                        'resize': function () {
                            setTimeout(function () {
                                panel.setActiveItem(0);
                                if ($('#tjChart1').find('canvas').length === 0) {
                                    tjChart1 = echarts.init(document.getElementById('tjChart1'));
                                    var tjChart1Data = sf.getSankeyChartData();
                                    tjChart1.setOption(sf.getChartOption2(tjChart1Data));
                                } else {
                                    tjChart1.resize();
                                }
                                $('#tjChart2').highcharts(sf.getChartOption('1'));
                            }, 0);
                        }
                    }
                }]
            }]
        }).show();
    },
    // 用水参数设定
    nwParamsSet: function () {
        var me = this;
        Ext.create('Ext.window.Window', {
            title: '用水参数',
            width: 1200,
            modal: true,
            items: [{
                xtype: 'grid',
                margin: '0 5 5 5',
                reference: 'wdGrid4',
                loadMask: true,
                stripeRows: true,
                columnLines: true,
                forceFit: true, //表格自适应
                columns: [{
                    text: '用水区域', dataIndex: 'adCd', align: 'center',
                    renderer: function (value) {
                        return me.formatAdCdToName(value);
                    }
                }, {
                    text: '生活用水漏损率（%）',
                    columns: [{
                        text: '城市供水漏损率', dataIndex: 'dWsLr', editor: 'numberfield', align: 'right'
                    }, {
                        text: '乡镇集中供水漏损率', dataIndex: 'crwsLr', editor: 'numberfield', align: 'right'
                    }]
                }, {
                    text: '乡镇集中供水率（%）', dataIndex: 'crwsR', editor: 'numberfield', align: 'right'
                }, {
                    text: '水田灌溉水利用系数', dataIndex: 'pwirR', editor: 'numberfield', align: 'right'
                }, {
                    text: '水浇地灌溉水利用系数', dataIndex: 'pdirR', editor: 'numberfield', align: 'right'
                }, {
                    text: '菜田灌溉水利用系数', dataIndex: 'pvirR', editor: 'numberfield', align: 'right'
                }, {
                    text: '林果地灌溉水利用系数', dataIndex: 'fiR', editor: 'numberfield', align: 'right'
                }, {
                    text: '草地灌溉水利用系数', dataIndex: 'aiR', editor: 'numberfield', align: 'right'
                }, {
                    text: '工业用水漏损率（%）', dataIndex: 'indLr', editor: 'numberfield', align: 'right'
                }],
                store: Ext.data.StoreManager.lookup('wdp_store4'),
                plugins: {
                    ptype: 'cellediting',
                    clicksToEdit: 1
                },
                listeners: {
                    edit: function () {
                        me.clacDeatilNeedWater();
                    }
                }
            }]
        }).show();
    },
    monthParamsSet: function () {
        var me = this;
        Ext.create('Ext.window.Window', {
            title: '逐月分配系数设置',
            width: 700,
            modal: true,
            items: [{
                xtype: 'grid',
                margin: '0 5 5 5',
                loadMask: true,
                stripeRows: true,
                columnLines: true,
                forceFit: true, //表格自适应
                columns: [{
                    text: '月份', dataIndex: 'month', align: 'center'
                }, {
                    text: '生活', dataIndex: 'pwmCoe', editor: 'textfield', align: 'right'
                }, {
                    text: '农业', dataIndex: 'awmCoe', editor: 'textfield', align: 'right'
                }, {
                    text: '林牧渔', dataIndex: 'lmyCoe', editor: 'textfield', align: 'right'
                }, {
                    text: '工业', dataIndex: 'iwmCoe', editor: 'textfield', align: 'right'
                }],
                store: Ext.data.StoreManager.lookup('wdp_store5'),
                plugins: {
                    ptype: 'cellediting',
                    clicksToEdit: 1
                },
                listeners: {
                    edit: function () {
                        me.clacMonthNeedWater();
                    }
                }
            }]
        }).show();
    },
    activeDetailTab: function (event) {
        // var me = this;
        // if (Ext.getCmp('wdpTab').activeItem == 0 && !me.getView().getCalBtnClickListener()) {
        //     me.getView().setCalBtnClickListener(true);
            
        // }
        
        // if (Ext.getCmp('wdpTab').activeItem !== 0 && !me.getView().getCalResult()) {
        //     var msg = "请先点击计算查看结果！";
        //     Ext.Msg.confirm("确认", msg, function (res) {});
        //     // event.stopPropagation();
        // }
    },
    /* tab-content2 */
    initWdTab2: function () {
        var me = this;
        me.changeWdTab2Chart();
    },
    selectChart: function () {
        Ext.getCmp('wd-tab2-chart-panel').fireEvent('resize');
    },
    changeWdTab2Chart: function (dom) {
        var me = this;
        var domid;
        if (this.wdtab2ChartId !== null) {
            domid = this.wdtab2ChartId;
        } else {
            if (typeof dom.el === 'object') {
                domid = dom.el.id + '-body';
                this.wdtab2ChartId = domid;
            } else {
                return;
            }
        }
        var type = Ext.getCmp('waterTypeSelect').getValue();
        me.nwdChart.gridData = Ext.data.StoreManager.lookup('wdp_store6').getData().items;
        var gridDataLen = type === '1' ? me.nwdChart.gridData.length : 3;
        $('#' + domid).html('');
        var html = $('#' + domid);
        var row;
        var colNum = 4;
        var rowNum = -1;
        var h = 100 / Math.ceil(gridDataLen / 3);
        for (var i = 0; i < gridDataLen; i++) {
            if (i === 0 || i % 3 === 0) {
                row = $('<div class="row-chart" style="height: ' + h +'%;"></div>');
                html.append(row);
                rowNum++;
            }
            var tempNum = Math.floor((gridDataLen - rowNum * 3) / 3);
            if (tempNum === 0) {
                colNum = 12 / (gridDataLen - rowNum * 3);
            } else if (tempNum > 0) {
                colNum = 4;
            }
            row.append($('<div style="height: 100%;" id="wd-tab2-chart-' + (i + 1) + '"></div>')
                .css({'flex': (colNum / 12) + '%'}));
        }

        if (type === '1') {
            var chartData = me.nwdChart.parseDataByArea(me, me.formatRegCdToName);
            $.each(chartData, function (index, item) {
                var name = item.area + '比例图';
                var data = item.data;
                $('#wd-tab2-chart-' + (index + 1)).highcharts(me.nwdChart.getChartOption(name, data));
            });
        } else if (type === '2') {
            var chartData = me.nwdChart.parseDataByType(me, me.formatRegCdToName);
            $.each(chartData, function (index, item) {
                var name = item.type + '比例图';
                var data = item.data;
                $('#wd-tab2-chart-' + (index + 1)).highcharts(me.nwdChart.getChartOption(name, data));
            });
        }
    },
    buildTab3Chart: function (dom) {
        var domId = '';
        if (typeof dom.el === 'object' && dom.el.hasOwnProperty('id')) {
            domId = dom.el.id + '-body';
            this.tab3ChartId = domId;
        } else {
            domId = this.tab3ChartId;
        }
        if (domId) {
            var data = Ext.data.StoreManager.lookup('wdp_store7').getData().items
            var life = [], agri = [], lgd = [], ind = [];
            $.each(data, function (index, obj) {
                obj = obj.data;
                var tLife = obj.dWat + obj.uWat + obj.bhWat + obj.shWat;
                var tAgri = obj.pwirWat + obj.pdirWat + obj.pvirWat;
                var tLgd = obj.fiWat + obj.aiWat + obj.fishWat;
                var tInd = obj.indWat + obj.nindWat;
                life.push(tLife);
                agri.push(tAgri);
                lgd.push(tLgd);
                ind.push(tInd);
            });
            $('#' + domId).highcharts({
                title: {
                    text: '逐月需水曲线图',
                    x: -20
                },
                xAxis: {
                    categories: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
                },
                yAxis: {
                    title: {
                        text: ''
                    },
                    plotLines: [{
                        value: 0,
                        width: 1,
                        color: '#808080'
                    }]
                },
                tooltip: {
                    // valueSuffix: '°C'
                },
                legend: {
                    layout: 'horizontal',
                    align: 'center',
                    verticalAlign: 'bottom',
                    borderWidth: 0
                },
                series: [{
                    name: '生活需水',
                    data: life
                },
                {
                    name: '农业需水',
                    data: agri
                },
                {
                    name: '林牧渔需水',
                    data: lgd
                },
                {
                    name: '工业需水',
                    data: ind
                }
                ],
                credits: {
                    enabled: false
                }
            });
        }
    }
})
